//
//  KaoNewsViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-2-25.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "MeterialListViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "MeterialDetailViewController.h"
#import "SearchHistroy.h"
#import "asyncimageview.h"
#import "CityShowViewController.h"
#import "MainTabBarController.h"

#define TopMoreViewH 160
#define TopViewH 38
#define SearchH 44
#define CityTag 35

@interface MeterialListViewController ()

@end

@implementation MeterialListViewController

- (id)init
{
    if (self = [super init]) {
        // Custom initialization
        _ShowAsyArr = [[NSMutableArray alloc] init];
        _ShowDataArr = [[NSMutableArray alloc] init];
        _SearchDataArr = [[NSMutableArray alloc] init];
        _SearchHisArr = [[NSMutableArray alloc] init];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onChangeProResponse:)
                                                     name:NotProChg
                                                   object:nil];
    }
    return self;
}

-(void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_ShowAsyArr release];
    [_ClearHisBtt release];
    [_SearchHisArr release];
    [_SearchDataArr release];
    [_SearchTableView release];
    [_ShowIDArr release];
    [_MoreTopView release];
    [_TopView release];
    [_SearchView release];
    [_ShowDataArr release];
    [_TagImgView release];
    [_SearchBtt release];
    [_NavBtt release];
    [_kaoTableView release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    _requestTypeIndex = 0;
    _SearchShowType = 0;
	// Do any additional setup after loading the view.
//    UILabel* tNavTitleLab = (UILabel*)[self.navigationController.navigationBar viewWithTag:144];
//    [tNavTitleLab setText:@"学习资料"];
    m_titleBttBarItem = [[MainTabBarController setTitle:@"学习资料"] retain];
    
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    //上部按钮
    _TopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, TopViewH)];
    [_TopView setBackgroundColor:[UIColor colorWithRed:235/255.f green:227/255.f blue:205/255.f alpha:1]];
    [self.view addSubview:_TopView];
    
    CALayer* tCLineLay = [CALayer layer];
    tCLineLay.frame =CGRectMake(56, 0, 1, TopViewH);
    [tCLineLay setBackgroundColor:BACKGROUND_COLOR.CGColor];
    [_TopView.layer addSublayer:tCLineLay];
    
    UIImageView* tMoreImgView = [[UIImageView alloc] initWithFrame:CGRectMake(40, (TopViewH-4)/2, 7, 4)];
    [tMoreImgView setImage:[UIImage imageNamed:@"more.png"]];
    [_TopView addSubview:tMoreImgView];
    [tMoreImgView release];
    UILabel* tKaoLab = [[UILabel alloc] initWithFrame:CGRectMake(4, (TopViewH-16)/2, 34, 16)];
    [tKaoLab setBackgroundColor:[UIColor clearColor]];
    [tKaoLab setText:@"国考"];
    tKaoLab.textAlignment = UITextAlignmentRight;
    [tKaoLab setFont:[UIFont systemFontOfSize:14]];
    [tKaoLab setTextColor:[UIColor darkGrayColor]];
    tKaoLab.tag = CityTag;
    [_TopView addSubview:tKaoLab];
    [tKaoLab release];
    UIButton* tKaoBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    tKaoBtt.frame =CGRectMake(4, 0, 46, TopViewH);
    [tKaoBtt addTarget:self action:@selector(kaoBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [_TopView addSubview:tKaoBtt];
    
    UIButton* tMoreBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [tMoreBtt setImage:[UIImage imageNamed:@"sort.png"] forState:UIControlStateNormal];
    [tMoreBtt addTarget:self action:@selector(showMoreView) forControlEvents:UIControlEventTouchUpInside];
    tMoreBtt.frame =CGRectMake(290, (TopViewH-24)/2, 24, 24);
    [_TopView addSubview:tMoreBtt];
    
    _TagImgView = [[UIImageView alloc] initWithFrame:CGRectMake(96, TopViewH-5, 10, 5)];
    [_TagImgView setImage:[UIImage imageNamed:@"trg.png"]];
    [_TopView addSubview:_TagImgView];
    //搜索
    _SearchView = [[UIView alloc] initWithFrame:CGRectMake(0, -SearchH, 320, SearchH)];
    UISearchBar* tSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, SearchH)];
    tSearchBar.tag =0x10;
    tSearchBar.delegate = self;
    tSearchBar.tintColor =[UIColor lightGrayColor];
    [_SearchView addSubview:tSearchBar];
    [tSearchBar release];
    [self.view addSubview:_SearchView];
    //更多按钮
    _MoreTopView = [[UIView alloc] initWithFrame:CGRectMake(0, TopViewH-TopMoreViewH, 320, TopMoreViewH)];
    [_MoreTopView setBackgroundColor:[UIColor colorWithRed:247/255.f green:241/255.f blue:226/255.f alpha:1]];
    [self.view addSubview:_MoreTopView];
    [self.view sendSubviewToBack:_MoreTopView];
    
    //cell
    _kaoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, TopViewH, 320, self.view.frame.size.height-44-TopViewH) style:UITableViewStylePlain];
    _kaoTableView.delegate = self;
    _kaoTableView.dataSource = self;
    _kaoTableView.separatorColor = SEPARATOR_COLOR;
    [_kaoTableView setBackgroundColor:BACKGROUND_COLOR];
    [self.view addSubview:_kaoTableView];
    
    _SearchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SearchH, 320, self.view.frame.size.height-44-SearchH) style:UITableViewStylePlain];
    _SearchTableView.delegate = self;
    _SearchTableView.dataSource = self;
    _SearchTableView.hidden =YES;
    [self.view addSubview:_SearchTableView];
    
    _ClearHisBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_ClearHisBtt addTarget:self action:@selector(clearHisSearch) forControlEvents:UIControlEventTouchUpInside];
    [_ClearHisBtt setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_ClearHisBtt setTitle:@"清除搜索记录" forState:UIControlStateNormal];
    _ClearHisBtt.frame =CGRectMake(0, 0, 320, 40);
    [_ClearHisBtt retain];
    [self setCityLab];
    [self requestIDData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
    [self.navigationController.navigationBar addSubview:_SearchBtt];
    [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [_SearchBtt removeFromSuperview];
    [m_titleBttBarItem removeFromSuperview];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) setCityLab
{
    UILabel* tCityLab = (UILabel*)[_TopView viewWithTag:CityTag];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* tEnumCityStr = nil;
    for (NSDictionary* tCityDic in tAppDel.m_CityDataArr) {
        tEnumCityStr = [NSString stringWithFormat:@"%d",[[tCityDic objectForKey:@"id"] intValue]];
        if ([tEnumCityStr isEqualToString:tAppDel.m_Province_id]) {
            [tCityLab setText:[tCityDic objectForKey:@"name"]];
            return;
        }
    }
    
}

- (void)onChangeProResponse:(NSNotification *)notification
{
    [self setCityLab];
    [self requestIDData];
}

//考点击
-(void) kaoBttPressed
{
    CityShowViewController* tCityVC = [[CityShowViewController alloc] init];
    tCityVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tCityVC animated:YES];
    [tCityVC release];
}

//更多按钮显示
-(void) showMoreView
{
    [UIView beginAnimations:nil context:nil];
    CGRect aFrame = CGRectZero;
    if (_MoreTopView.frame.origin.y < 0) {
        //出现
        aFrame = _MoreTopView.frame;
        aFrame.origin.y =TopViewH+_TopView.frame.origin.y;
        _MoreTopView.frame = aFrame;
        
        aFrame = _kaoTableView.frame;
        aFrame.origin.y += TopMoreViewH;
        aFrame.size.height -= TopMoreViewH;
        _kaoTableView.frame = aFrame;
        
    }else{
        //消失
        aFrame = _MoreTopView.frame;
        aFrame.origin.y =TopViewH-TopMoreViewH+_TopView.frame.origin.y;
        _MoreTopView.frame = aFrame;
        
        aFrame = _kaoTableView.frame;
        aFrame.origin.y -= TopMoreViewH;
        aFrame.size.height += TopMoreViewH;
        _kaoTableView.frame = aFrame;
    }
    [UIView commitAnimations];
}
//专题数据切换
-(void) changeModeNews:(UIButton*)f_sender
{
    int tTypeIndex = f_sender.tag-10;
    if (_requestTypeIndex != tTypeIndex) {
        [UIView beginAnimations:nil context:nil];
        int tTypeIndex = f_sender.tag-10;
        CGRect aFrame =_TagImgView.frame;
        aFrame.origin.x = 96+tTypeIndex*74;
        _TagImgView.frame = aFrame;
        [UIView commitAnimations];
        [_ShowAsyArr removeAllObjects];
        [_ShowDataArr removeAllObjects];
        _requestTypeIndex =f_sender.tag-10;
        NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getMeterial&category_id=%@&page=1&pageSize=20",RequestCurrentURL,[[_ShowIDArr objectAtIndex:_requestTypeIndex] objectForKey:@"id"]];
        [self requestListData:tURLStr];
    }
    
}
//所有的标题
-(void) totallSubjectPressed:(UIButton*)f_sender
{
    if (_requestTypeIndex != f_sender.tag) {
        _requestTypeIndex =f_sender.tag;
        [_ShowAsyArr removeAllObjects];
        [_ShowDataArr removeAllObjects];
        NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getMeterial&category_id=%@&page=1&pageSize=20",RequestCurrentURL,[[_ShowIDArr objectAtIndex:_requestTypeIndex] objectForKey:@"id"]];
        [self requestListData:tURLStr];
        [self showMoreView];
    }
    
}
#pragma mark-
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString* tURLStr  = nil;
    NSString*  tNewsID = nil;

        NSDictionary* tDic = [_ShowDataArr objectAtIndex:indexPath.row];
        tURLStr = [NSString stringWithFormat:@"%@ac=getNewsDetail&id=%d&catid=%d",RequestCurrentURL,[[tDic objectForKey:@"id"] intValue],[[tDic objectForKey:@"category_id"] intValue]];
        tNewsID = [tDic objectForKey:@"id"];

    MeterialDetailViewController* tWebNewsVC = [[MeterialDetailViewController alloc] init];
    tWebNewsVC.m_HttpURL =tURLStr;
    tWebNewsVC.m_NewsID = tNewsID;
    tWebNewsVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tWebNewsVC animated:YES];
    [tWebNewsVC release];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
#pragma mark-
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _SearchTableView) {
        if (_SearchShowType == 0) {
            return [_SearchHisArr count];
        }else if(_SearchShowType == 1){
            return [_SearchDataArr count];
        }
    }else{
        return [_ShowDataArr count];
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* tCell= nil;
    int tRow = indexPath.row;

        static NSString* s_CellStr = @"kcell";
        tCell = [tableView dequeueReusableCellWithIdentifier:s_CellStr];
        if (tCell  == nil) {
            tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:s_CellStr] autorelease];
            UILabel* tTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(16, 12, 288,20)];
            [tTitleLab setBackgroundColor:[UIColor clearColor]];
            [tTitleLab setFont:[UIFont systemFontOfSize:16]];
            tTitleLab.tag =50;
            [tCell addSubview:tTitleLab];
            [tTitleLab release];
            
        }
        for (id tSubObject in tCell.subviews) {
            if ([tSubObject isKindOfClass:[AsyncImageView class]]) {
                [tSubObject removeFromSuperview];
            }
        }

        UILabel* tTitleLab = (UILabel*)[tCell viewWithTag:50];
        if (tRow < [_ShowDataArr count]) {
            [tTitleLab setText:[[_ShowDataArr objectAtIndex:tRow] objectForKey:@"title"]];
            //tTitleLab.frame =CGRectMake(16, 12, 288,20);
        }
    tCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return tCell;
}
#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if ([scrollView isEqual:_kaoTableView]) {
        int tPosyH =scrollView.contentSize.height-scrollView.frame.size.height;
        if (tPosyH < 0) {
            tPosyH = 0;
        }
        if (scrollView.contentOffset.y > tPosyH+30) {
            NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getMeterial&category_id=%@&page=%d&pageSize=20",RequestCurrentURL,[[_ShowIDArr objectAtIndex:_requestTypeIndex] objectForKey:@"id"],_NowPage];
            [self requestListData:tURLStr];
        }
    }
}

#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}

-(void) requestIDData
{
    [self addHudLoad];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getMeterialCategory&province_id=%@",RequestCurrentURL,tAppDel.m_Province_id];
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestListFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestIDFinish:)];
    [tRequestPage startAsynchronous];
}
-(void) requestIDFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            _ShowIDArr =[tRealDataDic objectForKey:@"list"];
            [_ShowIDArr retain];
            for (int i=0; i<[_ShowIDArr count]; i++) {
                UIButton* tMoreBtt = [UIButton buttonWithType:UIButtonTypeCustom];
                tMoreBtt.frame =CGRectMake(5+(i%2)*160, 8+i/2*38, 150, 30);
                tMoreBtt.layer.borderWidth = 1;
                tMoreBtt.tag = i;
                tMoreBtt.layer.borderColor = [UIColor colorWithRed:220/255.f green:213/255.f blue:198/255.f alpha:1].CGColor;
                [tMoreBtt setTitle:[[_ShowIDArr objectAtIndex:i] objectForKey:@"name"] forState:UIControlStateNormal];
                [tMoreBtt setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                [tMoreBtt.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [tMoreBtt setBackgroundColor:[UIColor colorWithCGColor:[UIColor colorWithRed:235/255.f green:227/255.f blue:205/255.f alpha:1].CGColor]];
                [tMoreBtt addTarget:self action:@selector(totallSubjectPressed:) forControlEvents:UIControlEventTouchUpInside];
                [_MoreTopView addSubview:tMoreBtt];
            }
            [[_TopView viewWithTag:10] removeFromSuperview];
            [[_TopView viewWithTag:11] removeFromSuperview];
            [[_TopView viewWithTag:12] removeFromSuperview];
            for (int i=0; i<3; i++) {
                UIButton* tTitBtt = [UIButton buttonWithType:UIButtonTypeCustom];
                tTitBtt.frame =CGRectMake(64+i*74, (TopViewH-16)/2, 74, 16);
                [tTitBtt setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                [tTitBtt setTitle:[[_ShowIDArr objectAtIndex:i] objectForKey:@"name"] forState:UIControlStateNormal];
                [tTitBtt.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [tTitBtt addTarget:self action:@selector(changeModeNews:) forControlEvents:UIControlEventTouchUpInside];
                tTitBtt.tag = 10+i;
                [_TopView addSubview:tTitBtt];
            }
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:YES delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getMeterial&category_id=%@&page=1&pageSize=20",RequestCurrentURL,[[_ShowIDArr objectAtIndex:_requestTypeIndex] objectForKey:@"id"]];
    _NowPage = 1;
    [_ShowAsyArr removeAllObjects];
    [_ShowDataArr removeAllObjects];
    [self requestListData:tURLStr];
}


-(void) requestListData:(NSString*)f_URLStr
{
    [self addHudLoad];
    _NowPage++;
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:f_URLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestListFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestListFinish:)];
    [tRequestPage startAsynchronous];
}

-(void) requestListFail:(ASIHTTPRequest*)request
{
    _NowPage--;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestListFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            id tRealDataDic = [tDataDic objectForKey:@"data"];
            if ([tRealDataDic isKindOfClass:[NSDictionary class]]) {
                NSArray* tListArr =[tRealDataDic objectForKey:@"list"];
                for (NSDictionary* tDic in tListArr) {
                    NSString* tImgStr =[tDic objectForKey:@"image"];
                    if ([tImgStr length] > 0) {
                        AsyncImageView* tImgView = [[AsyncImageView alloc] initWithFrame:CGRectMake(240, 4, 70, 48)];
                        tImgView.m_BoolSetImage =YES;
                        tImgView._numStateRequested =need_Request;
                        tImgView._imageRequestURL =tImgStr;
                        [_ShowAsyArr addObject:tImgView];
                        [tImgView customLoadImageFromURL];
                        [tImgView release];
                    }else{
                        [_ShowAsyArr addObject:@""];
                    }
                }
                [_ShowDataArr addObjectsFromArray:[tRealDataDic objectForKey:@"list"]];
            }
            [_kaoTableView reloadData];
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:YES delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}


@end
